package com.xz.member.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.utils.SecurityUtils;
import com.xz.member.domain.MemberInfo;
import com.xz.member.domain.MemberLevel;
import com.xz.member.domain.RechargeActivity;
import com.xz.member.domain.RechargeActivityGift;
import com.xz.member.mapper.MemberInfoMapper;
import com.xz.member.mapper.MemberLevelMapper;
import com.xz.member.mapper.RechargeActivityGiftMapper;
import com.xz.member.mapper.RechargeActivityMapper;
import com.xz.member.param.MemberQueryParam;
import com.xz.member.service.IMemberInfoService;
import com.xz.member.service.IRechargeActivityService;
import com.xz.member.vo.MemberInfoVo;
import com.xz.member.vo.RechargeActivityVo;
import common.ECDateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 客户信息Service业务层处理
 *
 * @author xz
 * @date 2024-1-22 11:10:32
 */
@Service
public class RechargeActivityServiceImpl extends ServiceImpl<RechargeActivityMapper, RechargeActivity> implements IRechargeActivityService {

    @Resource
    private RechargeActivityGiftMapper rechargeActivityGiftMapper;
    @Resource
    private MemberLevelMapper memberLevelMapper;

    @Override
    public List<RechargeActivity> queryList(RechargeActivity activity) {
        return baseMapper.queryList(activity);
    }

    @Override
    public RechargeActivityVo activityDetailById(Long id){
        RechargeActivityVo vo = new RechargeActivityVo();
        RechargeActivity rechargeActivity = baseMapper.selectById(id);

        BeanUtils.copyProperties(rechargeActivity,vo);
        // 折扣最新的
        if(Objects.nonNull(rechargeActivity.getMemberLevelId())){
            MemberLevel memberLevel = memberLevelMapper.selectById(rechargeActivity.getMemberLevelId());
            BigDecimal discount = memberLevel.getDiscount();
            vo.setDiscount(discount);
        }
        // 判断是否有礼物
        if(rechargeActivity.getIfGift().equals(1)){
            List<RechargeActivityGift> listByActivityId = rechargeActivityGiftMapper.findListByActivityId(rechargeActivity.getId());
            vo.setGiftList(listByActivityId);
        }
        return vo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult addActivity(RechargeActivityVo rechargeActivityVo){
        RechargeActivity activity = new RechargeActivity();
        BeanUtils.copyProperties(rechargeActivityVo,activity);

        //根据活动时间设置状态
        setStatusByActivityTime(activity);

        BigDecimal totalValue = new BigDecimal("0.00");
        List<RechargeActivityGift> giftList = rechargeActivityVo.getGiftList();

        if(CollectionUtils.isNotEmpty(giftList)){
            totalValue = giftList.stream().map(RechargeActivityGift::getGiftValue)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        //  商品总价值
        activity.setGiftTotalValue(totalValue);
        activity.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        baseMapper.insert(activity);

        if(CollectionUtils.isNotEmpty(giftList)){
            for (RechargeActivityGift o:giftList) {
                o.setActivityId(activity.getId());
                rechargeActivityGiftMapper.insert(o);
            }
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 根据活动时间设置状态
     * @param activity
     */
    private void setStatusByActivityTime(RechargeActivity activity) {
        Integer status = activity.getStatus();
        if(null != status && status.equals(4)){
            return;
        }
        try {
            Date startDate = activity.getStartDate();
            Date endDate = activity.getEndDate();
            Date today = ECDateUtils.getCurrentDate();

            if (today.after(endDate)) {
                // 如果今天已经超过了活动结束日期，则状态为已结束
                status = 3;
            } else if (!today.before(startDate)) {
                // 如果今天不是活动开始日期之前（即今天等于或晚于开始日期），
                // 并且没有超过结束日期（已在上面的if条件中检查），则状态为进行中
                status = 2;
            } else {
                // 如果今天还在活动开始日期之前，则状态为未开始
                status =  1;
            }

            activity.setStatus(status);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateActivity(RechargeActivityVo rechargeActivityVo){
        if(Objects.isNull(rechargeActivityVo.getId())){
            return AjaxResult.error("参数不正确");
        }
        RechargeActivity activity = new RechargeActivity();
        BeanUtils.copyProperties(rechargeActivityVo,activity);
        //根据活动时间设置状态
        setStatusByActivityTime(activity);
        BigDecimal totalValue = new BigDecimal("0.00");
        // 先删除
        rechargeActivityGiftMapper.deleteByActivityId(activity.getId());
        // 再新增
        List<RechargeActivityGift> giftList = rechargeActivityVo.getGiftList();
        if(CollectionUtils.isNotEmpty(giftList)){
            for (RechargeActivityGift o:giftList) {
                totalValue = totalValue.add(o.getGiftValue());
                o.setActivityId(activity.getId());
                rechargeActivityGiftMapper.insert(o);
            }
        }
        // 更新商品总价值
        activity.setGiftTotalValue(totalValue);
        baseMapper.updateById(activity);
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult invalid(RechargeActivity rechargeActivity){
        if(Objects.isNull(rechargeActivity.getId())){
            return AjaxResult.error("参数不正确");
        }
        RechargeActivity activity = baseMapper.selectById(rechargeActivity.getId());
        activity.setStatus(rechargeActivity.getStatus());
        baseMapper.updateById(activity);
        return AjaxResult.success("操作成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int stopActivity(){
        int i1 = baseMapper.stopActivity();
        return baseMapper.startActivity();

    }
}
